{% extends 'baykeshop/base_site.html' %}

{% load i18n static %}

{% block title %}购物车{% endblock %}

{% block extrastyle %}
<style>
    .table td {
        vertical-align: middle;
    }
</style>
{% endblock %}

{% block breadcrumb %}
<div class="container">
    <nav class="breadcrumb is-marginless mt-3 mb-3 is-small" aria-label="breadcrumbs">
      <ul>
        <li><a href="{% url 'baykeshop:home' %}">首页</a></li>
        <li class="is-active"><a href="#" aria-current="page">购物车</a></li>
      </ul>
    </nav>
</div>
{% endblock %}

{% block container %}
{{ results|json_script:"carts-data" }}

<div id="carts">
    <div class="box is-radiusless" v-if="cartsData.length > 0">
        <template>
            <b-table
                checkable
                hoverable
                :is-row-checkable="(row) => Number(row.sku.stock) > Number(row.count)"
                :checked-rows.sync="checkedRows" 
                :data="cartsData">
                <b-table-column field="id" label="ID" v-slot="props">
                    {$ props.row.id $}
                </b-table-column>
                <b-table-column field="pic" label="商品图" v-slot="props">
                    <figure class="image is-128x128">
                        <b-image
                            :src="`${props.row.sku.pic}`"
                            :alt="props.row.sku.spu.title"
                            ratio="1by1"
                        ></b-image>
                    </figure>
                </b-table-column>
                <b-table-column field="title" label="标题" v-slot="props">
                    {$ props.row.sku.spu.title $}
                    <div class="is-flex">
                        <p class="mt-2 mr-3" v-for="spec, i in props.row.sku.options" :key="i">
                            <span class=" has-text-grey-light">
                                {$ spec.spec $}
                            </span>：<strong>{$ spec.name $}</strong> 
                        </p>
                    </div>
                </b-table-column>
                <b-table-column field="stock" label="库存" width="120" v-slot="props">
                    {$ props.row.sku.stock $}
                </b-table-column>
                <b-table-column field="price" label="单价" width="120" v-slot="props">
                    <span class="is-size-5 has-text-grey">¥</span>{$ props.row.sku.price $}
                </b-table-column>
                <b-table-column field="count" label="数量" v-slot="props">
                    <b-field>
                        <b-numberinput
                            @input="updateCartNum(props.row)"
                            controls-position="compact"
                            size="is-small"
                            type="is-light"
                            :min="1"
                            :max="props.row.sku.stock"
                            :editable='true'
                            v-model="props.row.count">
                        </b-numberinput>
                    </b-field>
                </b-table-column>
                <b-table-column field="total_price" label="小计" width="120" v-slot="props">
                    <span class="is-size-5 has-text-grey">¥</span>{$ parseFloat(props.row.sku.price * props.row.count).toFixed(2) $}
                </b-table-column>
                <b-table-column field="caozuo" label="操作" width="80" v-slot="props">
                    <button class="delete" @click="delCart(props.row)">删除</button>
                </b-table-column>

                <template #footer>
                    <div class="has-background-light is-flex is-align-items-center is-justify-content-space-between">
                        <div class="has-text-danger-dark ml-3">
                            已选<span class="is-size-4 pl-2 pr-2">{$ checkedRows.length $}</span>件商品 
                        </div>
                        <div class=" is-flex is-align-items-center has-text-danger-dark ">
                            <span class="is-size-5">合计：</span> <span class="is-size-3 pr-5">¥ {$ total $}</span>
                            <button 
                                class="button is-primary is-radiusless is-large pl-6 pr-6" 
                                :disabled="checkedRows.length > 0 ? false : true"
                                @click="cartBuy">
                                去结算
                            </button>
                        </div>
                    </div>
                </template>
            </b-table>
        </template>
    </div>
    <div class="has-text-centered has-text-danger is-size-5" v-else> 
        <img src="{% static 'baykeshop/img/noCart1.png' %}">
        <p> 亲，购物车还是空的哟~ </p>
        <a class=" button is-primary is-outlined mt-4" href="{% url 'baykeshop:home' %}">继 续 逛</a>
    </div>

</div>

{% endblock %}


{% block vue %}
    <script>
        var cartsData = JSON.parse(document.getElementById('carts-data').textContent);
        var carts = new Vue({
            el: '#carts',
            delimiters: ['{$', '$}'],
            data: {
                cartsData,
                checkedRows: [],  // 选择的动态
                total:0
            },
            created(){
                cartsData.forEach(item => {
                    if (item.count < item.sku.stock){
                        this.checkedRows.push(item)
                    }
                })
            },
            watch:{
               // 监听选中商品
               checkedRows: {
                    handler: function (rows, oldrows) {
                        let total = 0;
                        rows.forEach(row => {
                            total += row.sku.price * row.count
                        })
                        this.total = total.toFixed(2)
                    },
                    deep: true
                },

            },
            methods: {
                // 修改数量
                updateCartNum(row){
                    request({
                        url: row.detailurl,
                        method: 'patch',
                        data: {
                            count: row.count
                        }
                    }).then(res => {
                        if (res.status == 200) {
                            bayke.toastMessage('is-success', '修改成功！')
                        }
                    })
                },

                // 删除购物车
                delCart(row){
                    this.$buefy.dialog.confirm({
                        message: '是否确认删除该购物车商品！',
                        cancelText: '取消',
                        onConfirm: () => {
                            request({
                                url: row.detailurl,
                                method: 'delete',
                            }).then(res => {
                                if (res.status == 204){
                                    // 前端删除数组
                                    this.cartsData.forEach(item => {
                                        if (item.id == row.id){
                                            this.cartsData.splice(this.cartsData.indexOf(item), 1)
                                            this.checkedRows.splice(this.checkedRows.indexOf(item), 1)
                                            cartNum._data.cartcount = parseInt(cartNum._data.cartcount) - parseInt(row.num)
                                        }
                                    })
                                    bayke.toastMessage('is-success', '删除成功！')
                                }
                            })
                        }
                    })
                },

                // 购物车结算
                cartBuy(){
                    let cartids = []
                    this.checkedRows.forEach(el => {
                        cartids.push(el.id)
                    })
                    location.href = '{% url "baykeshop:confirm" %}?cartids='+`${cartids.join(',')}`
                }
            }
        })

    </script>
{% endblock %}
    